---
import { getLoadingLogoId, getLoadingIFrameId } from '@features/example-runner/utils/getLoadingLogoId';
interface Props {
    pageName: string;
    exampleName: string;
}

const { pageName, exampleName } = Astro.props as Props;
const loadingLogoId = getLoadingLogoId({ pageName, exampleName });
const loadingIFrameId = getLoadingIFrameId({ pageName, exampleName });
---

<script
    define:vars={{
        pageName,
        exampleName,
        loadingLogoId,
        loadingIFrameId,
    }}
>
    window.addEventListener('message', ({ data }) => {
        const isExample = pageName === data?.pageName && exampleName === data?.exampleName;
        if (!isExample) return;

        if (data?.type === 'init') {
            // FIXME - some pages have the same example on the page twice
            // this code works, but we should move off IDs so we can handle this case
            document.querySelectorAll('#' + loadingLogoId).forEach((loadingLogoId) => {
                loadingLogoId.remove();
            });
            document.querySelectorAll('#' + loadingIFrameId).forEach((iframe) => {
                iframe.style.visibility = 'visible';
                if (document.documentElement.dataset['darkMode'] === 'true') {
                    iframe.contentDocument.documentElement.dataset.darkMode = true;
                }
            });
        }
    });
</script>
